<?php


namespace BeReborn\Service\Process;

use BeReborn;
use BeReborn\Core\JSON;
use Exception;
use Swoole\Process as SProcess;
use Swoole\Timer;

/**
 * Class ServerLogger
 * @package BeReborn\Server
 */
class ServerLogger extends BeReborn\Service\Process
{

	/**
	 * @param SProcess $process
	 * @throws Exception
	 */
	public function onHandler(SProcess $process)
	{
		BeReborn::setProcessId($this->pid);
		Timer::tick(50, function () use ($process) {
			$redis = BeReborn::$app->redis;
			$socket = BeReborn::getWebSocket();
			try {
				$read = $process->read();
				$read = JSON::decode($read, true);
				if (empty($read)) {
					return;
				}

				$fds = $redis->sMembers('debug:list');
				if (empty($fds)) {
					return;
				}
				foreach ($read as $log) {
					foreach ($fds as $fd) {
						if (!$socket->isEstablished($fd)) {
							$redis->srem('debug:list', $fd);
						} else {
							$socket->push($fd, print_r($log, true));
						}
					}
				}
			} catch (\Throwable $exception) {
				print_r($exception->getMessage());
			}
		});
	}
}
